import json

from flask import Flask, Blueprint, Response, request
from flask_jwt_extended import create_access_token
from app.common.commonMessage import CommonMassages
from app.service.SysUserService import SysUserService
from app.config.db import DBUtils
from app.config.jsonEncoder import CustomJSONEncoder

app = Flask(__name__)
# 创建蓝图
login_bp = Blueprint('login_controller', __name__,url_prefix='/kshx')

sysUsers = SysUserService()

# 获取session
db_utils = DBUtils()
session = db_utils.get_session()

@login_bp.route('/login', methods=['POST'])
def login():
    username = request.json.get("username",None)
    password = request.json.get("password",None)

    if username is not None and password is not None:
        sysUser = sysUsers.select_data_by_username(session, username)
        if sysUser is not None:
            if sysUser.PASSWORD == password:
                # 生成JWT令牌
                access_token = create_access_token(identity={'username': sysUser.USERNAME, 'nickname': sysUser.NICKNAME})
                respResult = {
                    "code": 200,
                    "data": access_token,
                    "message": CommonMassages.USER_LOGIN_SUCCESS.value
                }
            else:
                respResult = {
                    "code": 400,
                    "data": None,
                    "message": CommonMassages.USER_USERNAME_PASSWORD_ERROR.value
                }
        else:
            respResult = {
                "code": 400,
                "data": None,
                "message": CommonMassages.USER_USERNAME_PASSWORD_ERROR.value
            }
    else:
        respResult = {
            "code": 400,
            "data": None,
            "message": CommonMassages.USERNAME_PASSWORD_ERROR.value
        }
    resp_data = json.dumps(respResult, ensure_ascii=False)
    return Response(resp_data, content_type='application/json')

@login_bp.route('/autologin', methods=['GET', 'POST'])
def autologin():
    username = request.args.get('username')
    if username == 'gspuser':
        sysUser = sysUsers.select_data_by_username(session, username)
        # 生成JWT令牌
        access_token = create_access_token(identity={'username': sysUser.USERNAME, 'nickname': sysUser.NICKNAME})
        respResult = {
            "code": 200,
            "data": access_token,
            "message": CommonMassages.USER_LOGIN_SUCCESS.value
        }
    else:
        respResult = {
            "code": 400,
            "data": None,
            "message": CommonMassages.USERNAME_PASSWORD_ERROR.value
        }
    resp_data = json.dumps(respResult, ensure_ascii=False, cls=CustomJSONEncoder)
    return Response(resp_data)